<!--
 * @Version: 2.0
 * @Author: zhao
 * @Date: 2022-06-20 15:19:22
 * @LastEditors: zhaosetChartNumber
 * @LastEditTime: 2022-06-30 16:56:12
-->
<template>
    <div>
        <el-tabs v-model="activeName" type="border-card" @tab-click="handleClickTab" :stretch="true">
            <el-tab-pane label="行政区划" name="first">
                <el-form ref="form" :model="form" label-width="60px">
                    <el-form-item label="省级">
                        <el-select
                            v-model="form.province"
                            value-key="name"
                            placeholder="请选择省"
                            clearable
                            @change="handleSelectChange($event, '省')"
                        >
                            <el-option v-for="item in provinceData" :key="item.name" :label="item.name" :value="item" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="地级市">
                        <el-select
                            v-model="form.city"
                            placeholder="请选择市"
                            value-key="name"
                            clearable
                            :disabled="cityDisabled"
                            @change="handleSelectChange($event, '市')"
                        >
                            <el-option v-for="item in cityData" :key="item.name" :label="item.name" :value="item" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="区县">
                        <el-select
                            v-model="form.area"
                            placeholder="请选择区县"
                            @change="handleSelectChange($event, '县')"
                            value-key="name"
                            clearable
                            :disabled="areaDisabled"
                        >
                            <el-option v-for="items in areaData" :key="items.name" :label="items.name" :value="items" />
                        </el-select>
                    </el-form-item>
                </el-form>
            </el-tab-pane>
            <el-tab-pane label="图幅号检索" name="second">
                <el-input v-model="form.MappableUnit" placeholder="请输入图幅号" clearable @blur="setChartNumber"></el-input>
                <el-tree
                    :props="props"
                    node-key="id"
                    :default-expanded-keys="expandedkeys"
                    :data="getChartNumber"
                    show-checkbox
                    @check-change="handleCheckChange"
                    @node-click="handleNodeClick"
                    ref="treeVerNew"
                    @check="menuCheck"
                    lazy
                    :load="loadNode"
                    empty-text="暂无数据"
                />
                <!-- lazy
                    :load="loadNode" -->
            </el-tab-pane>
            <el-tab-pane label="坐标检索" name="third">
                <el-form ref="form" :model="form" label-width="100px" :label-position="'top'" class="CoordinateRetrieval">
                    <el-form-item label="shp文件导入:">
                        <el-input v-model="form.ShpFile.name" clearable @clear="setClearable('ShpFile')" />
                        <input type="file" style="display: none" ref="ShpFile" @change="(checked) => handleClick(checked, 'ShpFile')" />
                        <el-button type="primary" size="medium" class="inquire" @click="getFile('ShpFile')">选择文件 </el-button>
                    </el-form-item>
                    <el-form-item label="文本导入:">
                        <el-input v-model="form.ShpFileText.name" clearable @clear="setClearable('ShpFileText')" />
                        <input type="file" style="display: none" ref="ShpFileText" @change="(checked) => handleClick(checked, 'ShpFileText')" />
                        <el-button type="primary" size="medium" class="inquire" @click="getFile('ShpFileText')">选择文件 </el-button>
                    </el-form-item>
                    <el-form-item label="坐标录入:">
                        <el-input v-model="form.desc" placeholder="输入格式：111.123,21.123,112.123,23.123" type="textarea" />
                    </el-form-item>
                    <div class="notes">
                        <p>注1：坐标以英文逗号区分</p>
                        <p>注2：第一个值为经度，第二个值为纬度，以此类推</p>
                        <p>注3：经度加纬度为一组，四组确定一个矩形</p>
                        <p>例：111,36,111,38,114,38,114,36</p>
                    </div>
                </el-form>
            </el-tab-pane>
        </el-tabs>
        <div class="but">
            <el-button type="primary" class="inquire" @click="onSubmit">查询</el-button>
            <el-button class="Cancel" @click="Repossess">重置</el-button>
        </div>
    </div>
</template>

<script>
import { thisExpression } from "@babel/types"

export default {
    components: {},
    props: {},
    data() {
        return {
            form: {
                ShpFileText: {},
                ShpFile: {},
            },
            activeName: "first",
            provinceData: [],
            cityData: [],
            areaData: [],
            props: {
                children: "children",
                label: "code",
                isLeaf: "leaf",
            },
            count: 1,
            treedata: [
                {
                    id: 99996,
                    code: "1/5万",
                    type: "E",
                    children: [],
                    disabled: true,
                },
                {
                    id: 99995,
                    code: "1/10万",
                    type: "D",
                    children: [],
                    disabled: true,
                },
                {
                    id: 99994,
                    code: "1/20万",
                    type: "R",
                    children: [],
                    disabled: true,
                },
                {
                    id: 99993,
                    code: "1/25万",
                    type: "C",
                    children: [],
                    disabled: true,
                },
                {
                    id: 99992,
                    code: "1/50万",
                    type: "B",
                    children: [],
                    disabled: true,
                },
                {
                    id: 99991,
                    code: "1/100万",
                    children: [],
                    type: "A",
                    disabled: true,
                },
            ],
            rawTreeData: [], //原始数据
            ChartNumber: "", //图幅号
            expandedkeys: [], //默认展开的el-tree
            currentNodekey: "", //选中数据
            areaDisabled: true, //区县禁用
            cityDisabled: true, //市禁用
            tiandiMap: null,
            map: null,
            areaCode: "",
        }
    },
    computed: {
        getChartNumber() {
            this.expandedkeys = []
            let data = this.zpublic.DeepCopyArr(this.treedata)

            if (!this.form.MappableUnit) {
                return data
            }
            const sdata = data.filter((e, index) => {
                e.children = e.children.filter((c) => c.code.indexOf(this.form.MappableUnit) != -1)
                if (e.children.length > 0) this.expandedkeys.push(e.id)
                return e
            })
            return sdata
        },
    },
    watch: {
        "$store.state.map.geometryCoordinate"(val) {
            let Pointsdata = {
                pageSize: this.$store.state.table.searchData.pageSize,
                pageIndex: this.$store.state.table.searchData.pageIndex,
                points: val,
            }
            this.getResultFromPoints(Pointsdata)
        },
        "$store.state.table.searchData": {
            handler: function (val, oldVal) {
                // this.onSubmit()
            },
            immediate: true,
            deep: true,
        },
        "$store.state.map.map"(val) {
            this.map = val
        },
        "$store.state.table.clearQueryCondition"(val) {
            if (val) this.form = { ShpFileText: {}, ShpFile: {} }
        },
    },
    activated() {
        // this.onSubmit()
    },
    mounted() {
        // this.initData()
        this.tiandiMap = this.$store.state.map.tiandiMap

        this.getChart()
        this.GetDivision().then((res) => {
            this.provinceData = res
        })
        this.$store.state.table.url = "map/getResultFromPoints"

        /*****  从属性查询 查看大图进来的 start *****/
        const pageType = this.$store.state.map.pageType

        if (pageType == "AttrilbuteQuery") {
            this.$store.state.table.searchData = {
                pageIndex: 1,
                pageSize: this.$store.state.table.searchData.pageSize,
            }
            return (this.$store.state.map.pageType = "")
        }
        if (pageType == "SpatialRetrieval") {
            // this.invertQueryData()
            return (this.$store.state.map.pageType = "")
        }
        /*****  从属性查询 查看大图进来的 end *****/
        // this.form.province = "河北省"
        this.$store.state.table.searchData = {
            points: this.getAreaPoints("130000"),
            area: "河北省",
            pageIndex: 1,
            pageSize: 10,
        }

        this.getResultFromPoints({
            points: this.getAreaPoints("130000"),
            area: "河北省",
            pageIndex: 1,
            pageSize: 10,
        })
        // this.handleClickTab()
    },
    methods: {
        handleClickTab(val) {
            this.$store.state.map.selectType = this.activeName
            this.$store.state.map.form = {}
            this.form = {
                ShpFileText: {},
                ShpFile: {},
            }
        },
        handleCheckChange(val, checked, node) {},
        handleNodeClick(val, checked, node) {
            if (checked.level == 2) {
                this.$refs.treeVerNew.setCheckedKeys([])

                if (this.currentNodekey == checked.data.code) {
                    this.currentNodekey = ""
                    this.$refs.treeVerNew.setCheckedKeys([])
                } else {
                    this.$refs.treeVerNew.setChecked(val, true)
                    this.currentNodekey = val.code
                }
            }
        },
        menuCheck(val, checked) {
            this.$refs.treeVerNew.setCheckedKeys([])
            if (this.currentNodekey == val.code) {
                this.currentNodekey = ""
                this.$refs.treeVerNew.setCheckedKeys([])
            } else {
                this.$refs.treeVerNew.setChecked(val, true)
                this.currentNodekey = val.code
                this.$store.state.table.searchData.currentNodekey = this.currentNodekey
                this.onSubmit()
            }
        },
        // async initData() {
        //     const { data } = await this.$store.dispatch("map/getDivision",)
        //     this.provinceData = data
        //     this.cityData = data[0].children

        // },
        handleSelectChange(item, val) {
            if (val === "省") {
                this.cityDisabled = false
                // this.form.city = {}
                // this.form.area = {}
                this.$set(this.form, "area", {})
                this.$set(this.form, "city", {})
                this.GetDivision({ id: item.area_number }).then((res) => {
                    this.cityData = res
                })
            }
            if (val === "市") {
                this.areaDisabled = false
                this.$set(this.form, "area", {})
                this.GetDivision({ id: item.area_number }).then((res) => {
                    this.areaData = res
                })
            }
            if (val === "区县") {
            }

            this.areaCode = item.area_number
            if (!item) {
                if (val == "省") this.areaCode = "130000"
                if (val == "市") this.areaCode = this.form.province.area_number
                if (val == "县") this.areaCode = this.form.city.area_number
            }

            this.onSubmit()
        },

        onSubmit() {
            this.setRightHide()
            this.delMarker()
            this.$store.state.map.selectType = this.activeName
            this.$store.state.map.form = this.form
            this.$store.state.map.isLeft = true //清空右侧查询
            setTimeout(() => {
                this.$store.state.map.isLeft = false
            }, 100)
            this.$store.state.table.url = "map/getResultFromPoints"
            // this.$store.state.table.searchData = {
            //     pageSize: 10,
            //     pageIndex: 1,
            // }
            if (this.activeName == "first" && this.form.province) {
                let Pointsdata = {
                    pageSize: this.$store.state.table.searchData.pageSize,
                    pageIndex: this.$store.state.table.searchData.pageIndex,
                    area: "",
                }
                if (this.form.province && this.form.province.name) Pointsdata.area = this.form.province.name
                if (this.form.city && this.form.city.name) Pointsdata.area += this.form.city.name
                if (this.form.area && this.form.area.name) Pointsdata.area += this.form.area.name
                Pointsdata.points = this.getAreaPoints(this.areaCode)
                this.$store.state.table.searchData = Pointsdata
                this.getResultFromPoints(Pointsdata)
            }
            if (this.activeName == "second") {
                this.getPointsFromMappableUnit()
            }
            if (this.activeName == "third") {
                this.getPointsFromShpFile()
            }
        },
        // 根据查询条件获取对应案卷信息
        async getResultFromPoints(Pointsdata) {
            // this.tiandiMap.clearLayers()
            this.$store.state.map.mapSearch = this.form
            const { data, count } = await this.$store.dispatch("map/getResultFromPoints", Pointsdata)
            this.$store.state.table.PaginationData.total = count
            data.map((e) => {
                e.LonLat = this.getCentralData(e.maxX, e.maxY, e.minX, e.minY)
            })
            this.$store.state.table.searchData = Pointsdata
            this.$store.state.map.mapList = data
        },
        // 根据图幅号获取对应点位信息
        async getPointsFromMappableUnit() {
            if (!this.currentNodekey) return this.$message.error("请选择图幅号")
            this.$store.state.map.mapSearch = this.form
            let mapdata = {
                MappableUnit: this.currentNodekey,
            }

            const { data } = await this.$store.dispatch("map/getPointsFromMappableUnit", mapdata)
            let Pointsdata = {
                pageSize: this.$store.state.table.searchData.pageSize,
                pageIndex: this.$store.state.table.searchData.pageIndex,
                points: [data],
            }
            this.$store.state.table.searchData = Pointsdata
            this.getResultFromPoints(Pointsdata)
            this.initLonLat(data)

            let zoom = null
            switch (this.currentNodekey.split("")[3]) {
                case "A":
                    zoom = 7
                    break
                case "B":
                    zoom = 7
                    break
                case "C":
                    zoom = 7
                    break
                case "D":
                    zoom = 8
                    break
                case "E":
                    zoom = 8
                    break
                case "R":
                    zoom = 8
                    break
                default:
                    zoom = 7
                    break
            }

            this.setMapView(zoom, this.getCentralData(data[0].x, data[0].y, data[2].x, data[2].y))
        },
        // 根据shp文件获取对应点位信息
        async getPointsFromShpFile() {
            this.$store.state.map.mapSearch = this.form
            if (this.form.ShpFile.name) {
                let formData1 = new FormData()

                formData1.append("ShpFile", this.form.ShpFile)
                const { data } = await this.$store.dispatch("map/getPointsFromShpFile", formData1)
                let Pointsdata = {
                    pageSize: this.$store.state.table.searchData.pageSize,
                    pageIndex: this.$store.state.table.searchData.pageIndex,
                    points: [data],
                }

                this.$store.state.table.searchData = Pointsdata
                this.getResultFromPoints(Pointsdata)
                this.initLonLat(data)
            }
            if (this.form.ShpFileText.name) {
                let formData2 = new FormData()
                formData2.append("ShpFile", this.form.ShpFileText)
                const { data } = await this.$store.dispatch("map/getPointsFromShpTxt", formData2)
                let Pointsdata = {
                    pageSize: this.$store.state.table.searchData.pageSize,
                    pageIndex: this.$store.state.table.searchData.pageIndex,
                    points: [data],
                }
                this.$store.state.table.searchData = Pointsdata
                this.getResultFromPoints(Pointsdata)
                this.initLonLat(data)
            }
            if (this.form.desc) {
                this.settextarea()
            }
        },
        setChartNumber() {},
        //获取中心坐标
        getCentralData(oneLon, oneLat, twoLon, twoLat) {
            //oneLon：第一个点的经度；oneLat：第一个点的纬度；twoLon：第二个点的经度；twoLat：第二个点的纬度；
            let aLon = 0,
                aLat = 0
            let bLon = Number(oneLon) - Number(twoLon)
            let bLat = Number(oneLat) - Number(twoLat)
            //Math.abs()绝对值
            if (bLon > 0) {
                aLon = Number(oneLon) - Math.abs(bLon) / 2
            } else {
                aLon = Number(twoLon) - Math.abs(bLon) / 2
            }
            if (bLat > 0) {
                aLat = Number(oneLat) - Math.abs(bLat) / 2
            } else {
                aLat = Number(twoLat) - Math.abs(bLat) / 2
            }
            return [aLon, aLat]
        },
        getFile(prop) {
            this.emptyCoordinateInput()
            this.$refs[prop].click()
        },
        //获取 选择的文件
        handleClick(e, prop) {
            const files = e.target.files[0]

            this.$set(this.form, prop, files)
            this.$refs[prop].value = ""
        },
        setClearable(val) {
            this.$store.state.table.searchData.points = []
            this.form[val] = {}
        },
        //坐标录入
        settextarea() {
            this.form.ShpFile = ""
            this.form.ShpFileText = ""
            var strs = []
            let data = this.form.desc.split(",")
            data.map((e, index) => {
                if (index % 2 == 0) {
                    var obj = {
                        x: e,
                        y: data[index + 1],
                    }
                    strs.push(obj)
                }
            })
            let Pointsdata = {
                pageSize: this.$store.state.table.searchData.pageSize,
                pageIndex: this.$store.state.table.searchData.pageIndex,
                points: [strs],
            }

            this.initLonLat(strs)
            this.$store.state.table.searchData = Pointsdata
            this.getResultFromPoints(Pointsdata)
            this.setMapView(6, this.getCentralData(strs[0].x, strs[0].y, strs[2].x, strs[2].y))
        },
        setRightHide() {
            this.$emit("setRightHide", 0)
        },
        //格式化坐标点
        initLonLat(data) {
            let lonlat = []
            data && data.map((e, index) => lonlat.push([e.x, e.y]))

            this.$store.state.map.geometryData = [lonlat]
        },
        //获取图幅号
        async getChart() {
            let val = {
                pageSize: 11110,
                pageIndex: 1,
                // "type": ""
            }

            const { data } = await this.$store.dispatch("map/getMappableUnitFromType", val)
            this.rawTreeData = data
            data.map((e) => {
                this.treedata.map((s) => {
                    if (s.type == e.type) {
                        s.children.push(e)
                    }
                })
            })
        },
        //设置地图中心点 与 缩放度
        setMapView(zoom, center) {
            this.$store.state.map.mapData.zoom = zoom
            this.$store.state.map.mapData.center = center
        },
        async GetDivision(val) {
            const { data } = await this.$store.dispatch("map/getDivision", val)

            return data
        },

        Repossess() {
            this.form = {
                ShpFileText: {},
                ShpFile: {},
            }
        },
        delMarker() {
            this.$store.commit("map/empty")
        },
        //获取区域坐标
        getAreaPoints(code) {
            let jsonDATA = require("@/assets/json/" + code + ".json")
            let newdata = []
            let length = 0
            jsonDATA.features[0].geometry.coordinates.map((e, index) => {
                if (length == index) newdata[index] = new Array()
                length++
                e[0].map((s) => {
                    newdata[index].push({
                        x: s[0],
                        y: s[1],
                    })
                })
            })

            return newdata
        },
        //
        emptyCoordinateInput() {
            this.form.ShpFile = ""
            this.form.ShpFileText = ""
            this.form.desc = ""
        },
        loadNode(node, resolve) {
            if (this.form.MappableUnit) {
                let data = this.rawTreeData.filter((e) => {
                    if (e.type == node.data.type) {
                        if (e.code.indexOf(this.form.MappableUnit) !== -1) {
                            e.leaf = true
                            return e
                        }
                    }
                })
                resolve(data)
                return
            }
            if (node.level == 2) return resolve([])
            setTimeout(() => {
                let data = this.rawTreeData.filter((e) => {
                    if (e.type == node.data.type) {
                        e.leaf = true
                        return e
                    }
                })
                resolve(data)
            }, 100)
        },
        //反显查询数据
        invertQueryData() {
            if (Object.values(this.$route.params).length > 0) {
                this.$store.state.table.searchData = this.$route.params
                if (this.$route.params.area) {
                    const sheng = this.$route.params.area.split("省")
                    const shi = sheng[1] && sheng[1].split("市")
                    const qu = shi[1] || ""
                    if (sheng) {
                        this.handleSelectChange({ area_number: 130000 }, "省")
                        this.form.province = sheng[0] + "省"
                    }
                    if (shi) {
                        this.handleSelectChange({ area_number: 130000 }, "市")
                        this.cityDisabled = false
                        this.form.city = shi[0] + "市"
                    }
                    if (qu) {
                        this.areaDisabled = false
                        this.form.area = qu
                    }
                }

                if (this.$route.params.area) {
                }
            }
        },
    },
}
</script>

<style scoped lang="scss">
.but {
    width: 100%;
    display: flex;
    padding-top: 20px;
    justify-content: center;
}

.el-tree {
    padding: 10px 0;
    max-height: calc(100vh - 6rem);
    overflow-y: scroll;

    &::-webkit-scrollbar {
        display: none;
    }

    ::v-deep .el-tree-node__label {
        font-size: 0.296rem !important;
    }

    ::v-deep .el-tree-node {
        padding: 10px 0;
        .el-checkbox__input.is-disabled {
            display: none;
        }
    }
}

.el-tabs {
    box-shadow: none;
    border: none;

    ::v-deep .el-tabs__header {
        background: #c1cce4;
        color: rgba(0, 0, 0, 0.65);
        border-bottom: 0.013333rem solid #fff;

        .el-tabs__item {
            font-size: 0.259rem;
            height: 100%;
            padding: 10px;
        }

        .el-tabs__nav {
            height: 0.8rem;
        }
    }

    .is-active {
        background: #fff !important;
    }

    ::v-deep .el-tabs__content {
        border: 1px solid #eee;
        margin: 10px;
    }
}

.el-form {
    .el-select,
    .el-textarea,
    .el-input {
        width: 100%;
    }
}

.CoordinateRetrieval {
    .el-form-item {
        // .el-input {
        //     width: 70%;
        // }
        ::v-deep .el-form-item__content {
            display: flex;
            justify-content: flex-start;

            .inquire {
            }
        }
    }
}

.inquire {
    color: #fff;
    background-color: #194485;
    border-color: #194485;
}

.Cancel:hover {
    color: #606266;
    background-color: #fff;
    border: 1px solid #194485;
}

.notes {
    color: #8b8b8b;
}
</style>
